#!/usr/bin/python
#
#    Copyright 2006 Andrew Wilkinson <aw@cs.york.ac.uk>.
#
#    This file is part of PyScobble (http://lastfm.indiegigs.co.uk/pyscrobble)
#
#    PyScobble is free software; you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation; either version 2.1 of the License, or
#    (at your option) any later version.
#
#    PyScobble is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with PyScobble; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import getpass
import socket
import sys

import scrobble
import time

def getRecentTracks(user):
    while True:
        try:
            return user.recenttracks
        except socket.error, m:
            if m[0] != 110:
                raise
            else:
                print "Timeout connecting to Last.fm"
                time.sleep(5*60)

def main():
    user = scrobble.User(sys.argv[1])

    reuser = []
    for ru in sys.argv[2:]:
        reuser.append(scrobble.User(ru))
        reuser[-1].passwd = getpass.getpass("Password for %s: " % (ru, ))

    new_tracks = getRecentTracks(user)
    if len(new_tracks) > 0:
        last_track = new_tracks[0]
        print last_track
    else:
        last_track = None

    tracks = []
    while True:
        time.sleep((5 if len(tracks) == 0 else 3)*60)

        new_tracks = getRecentTracks(user)
        if len(new_tracks) == 0:
            last_track = None
            continue
        if last_track is None:
            tracks.extend(new_tracks)
        else:
            for t in new_tracks:
                if t == last_track:
                    break
                tracks.append(t)
        last_track = new_tracks[0]
        if len(tracks) > 0:
            t, tracks = tracks[0], tracks[1:]
            print t
            for u in reuser:
                u.scrobble(t[0], t[1])

if __name__ == "__main__":
    main()
